#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QDebug>
#include <QFileDialog>
#include <QDropEvent>
#include <QDragEnterEvent>
#include <QMimeData>

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow) {
  ui->setupUi(this);
  setAcceptDrops(true);
  ui->imgView->setInfo(ui->sInfo);
  connect(ui->dicomdirWidget, SIGNAL(sendImagePath(QTreeWidgetItem*,int)), ui->imgView, SLOT(receiveImagePath(QTreeWidgetItem*,int)));
}

MainWindow::~MainWindow() {
  delete ui;
}

void MainWindow::commandLine(int argc, char * argv[]) {
  if( argc > 2 ) {
    QString msg("Invalid commandline input!\nUsage: " + QString(argv[0]) + " <dcm image file>.");
    qDebug() << msg;
    ui->statusBar->showMessage(msg,Timeout);
    return;
  }
  if( argc == 2 ) {
    QFileInfo info( argv[1]);
    if( info.completeSuffix() == "dcm") {
      if(!ui->imgView->showImage(argv[1])) {
        QString msg("Error opening image " + QString(argv[1]) + ".");
        qDebug() << msg;
        ui->statusBar->showMessage(msg,Timeout);
      }
    } else {
      if(!ui->dicomdirWidget->addDicomdir(argv[1])) {
        QString msg("Error opening dicomdir" + QString(argv[1]) + ".");
        qDebug() << msg;
        ui->statusBar->showMessage(msg,Timeout);
      }
    }
  }
}

void MainWindow::on_actionOpen_Image_triggered() {
  QString filename = QFileDialog::getOpenFileName(this,"Open DICOM image",QDir::homePath(),"*.dcm");
  if(!ui->imgView->showImage(filename)) {
    QString msg("Error opening " + QString(filename) + ".");
    qDebug() << msg;
    ui->statusBar->showMessage(msg,Timeout);
  }
}

void MainWindow::dropEvent(QDropEvent *event) {
  statusBar()->showMessage("Drop event received!");
  const QMimeData* mimeData = event->mimeData();
  // check for our needed mime type, here a file or a list of files
  if (mimeData->hasUrls()) {
    QStringList pathList;
    QList<QUrl> urlList = mimeData->urls();
    // extract the local paths of the files
    for (int i = 0; i < urlList.size() && i < 32; ++i) {
      pathList.append(urlList.at(i).toLocalFile());
    }
    // call a function to open the files
    openFiles(pathList);
  }
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
  if (event->mimeData()->hasFormat("text/plain"))
    event->acceptProposedAction();
}

void MainWindow::openFiles(QStringList &files) {
  if(!ui->imgView->showImage(files.front())) {
    QString msg("Error opening " + files.front() + ".");
    qDebug() << msg;
    ui->statusBar->showMessage(msg,Timeout);
  }
}

void MainWindow::on_actionOpen_Dicomdir_triggered() {
  QString filename = QFileDialog::getOpenFileName(this,"Open DICOM image",QDir::homePath(),"*");
  if(!ui->dicomdirWidget->addDicomdir(filename)) {
    QString msg("Error opening dicomdir" + filename);
    qDebug() << msg;
    ui->statusBar->showMessage(msg,Timeout);
  }
}
